package com.itheima.protocol.CountDownLatch;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 上述代码中我们先生成了一个CountDownLatch实例。计数数量为10，这表示需要有10个线程来完成任务，
 * 等待在CountDownLatch上的线程才能继续执行。latch.countDown();方法作用是通知CountDownLatch
 * 有一个线程已经准备完毕，倒计数器可以减一了。latch.await()方法要求主线程等待所有10个检查任务
 * 全部准备好才一起并行执行
 */

public class CountDownLatchDemo implements Runnable {


    private final static CountDownLatch countDownLatch = new CountDownLatch(10);
    private static CountDownLatchDemo countDownLatchDemo = new CountDownLatchDemo();


    @Override
    public void run() {

        try {
            //模拟检查任务
            Thread.sleep(new Random().nextInt(10) * 1000);
            System.out.println("check complete");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //计数减一
            //放在finally避免任务执行过程出现异常，导致countDown()不能被执行
            countDownLatch.countDown();
        }
    }

    public static void main(String[] args) throws InterruptedException {

        ExecutorService exec = Executors.newFixedThreadPool(10);
        for (int i=0; i<10; i++){
            exec.submit(countDownLatchDemo);
        }

        // 等待检查
        countDownLatch.await();

        // 发射火箭
        System.out.println("Fire!");
        // 关闭线程池
        exec.shutdown();
    }
}


